package com.grade.system.service.impl;

import java.lang.reflect.Array;
import java.text.MessageFormat;
import java.util.*;

import com.grade.common.constant.Constants;
import com.grade.common.core.domain.Ztree;
import com.grade.common.core.domain.entity.SysMenu;
import com.grade.common.utils.DateUtils;
import com.grade.common.utils.StringUtils;
import com.grade.system.domain.GradeTemplate;
import com.grade.system.domain.GradeType;
import com.grade.system.domain.ItemTemplateRelation;
import com.grade.system.mapper.GradeTemplateMapper;
import com.grade.system.mapper.GradeTypeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.grade.system.mapper.GradeItemMapper;
import com.grade.system.domain.GradeItem;
import com.grade.system.service.IGradeItemService;
import com.grade.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 评分指标项Service业务层处理
 * 
 * @author grade
 * @date 2021-10-17
 */
@Service
public class GradeItemServiceImpl implements IGradeItemService 
{
    @Autowired
    private GradeItemMapper gradeItemMapper;
    @Autowired
    private GradeTypeMapper gradeTypeMapper;
    @Autowired
    private GradeTemplateMapper gradeTemplateMapper;

    /**
     * 查询评分指标项
     * 
     * @param id 评分指标项主键
     * @return 评分指标项
     */
    @Override
    public GradeItem selectGradeItemById(Long id)
    {
        return gradeItemMapper.selectGradeItemById(id);
    }

    /**
     * 查询评分指标项列表
     * 
     * @param gradeItem 评分指标项
     * @return 评分指标项
     */
    @Override
    public List<GradeItem> selectGradeItemList(GradeItem gradeItem)
    {
        return gradeItemMapper.selectGradeItemList(gradeItem);
    }

    @Override
    public List<GradeItem> selectItemAll()
    {
        return gradeItemMapper.selectItemAll();
    }

    @Override
    public List<Ztree> itemTreeData(Long userId)
    {
        List<GradeItem> itemList = selectItemAll();
        List<GradeType> typeList = gradeTypeMapper.selectGradeTypeAll();
        List<Ztree> ztrees = initZtree(itemList,typeList);
        return ztrees;
    }

    /**
     * 对象转菜单树
     *
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<GradeItem> itemList,List<GradeType> typeList)
    {
        return initZtree(itemList,typeList, null, false);
    }

    /**
     * 对象转菜单树
     *
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag 是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<GradeItem> itemList,List<GradeType> typeList, List<String> roleMenuList, boolean permsFlag)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (GradeType type : typeList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(type.getTypeId());
            ztree.setpId(type.getParentId());
            ztree.setName(transTypeName(type, true));
            ztree.setTitle(type.getTypeName());
            if (isCheck)
            {
                ztree.setChecked(roleMenuList.contains(type.getTypeId()));
            }
            ztrees.add(ztree);

        }
            for(GradeItem item : itemList){

                    Ztree itemTree = new Ztree();
                    itemTree.setId(item.getId()+ Constants.ID_ADD);
                    itemTree.setpId(item.getTypeId());
                    String content = item.getItemContent();
                    content = content.length()>10?content.substring(0,10):content;
                    itemTree.setName("<font color=\"#FF0000\">&nbsp;&nbsp;&nbsp;"+content + "</font>");
                    itemTree.setTitle(content);
                    ztrees.add(itemTree);
                }
        return ztrees;
    }


    public String transTypeName(GradeType type, boolean permsFlag)
    {
        StringBuffer sb = new StringBuffer();
        if (permsFlag)
        {
            sb.append("<font color=\"#888\">" +type.getTypeName() + "</font>");
        }
        return sb.toString();
    }
    /**
     * 新增评分指标项
     * 
     * @param gradeItem 评分指标项
     * @return 结果
     */
    @Override
    @Transactional
    public int insertGradeItem(GradeItem gradeItem)
    {
        gradeItem.setCreateTime(DateUtils.getNowDate());
        int layer = assembleItemSixColumn(gradeItem);
        //和template的layer对比如果更大就更新
        GradeTemplate gradeTemplate = gradeTemplateMapper.selectGradeTemplateById(gradeItem.getTemplateId());
        if(gradeTemplate.getLayer()<layer){
            GradeTemplate template = new GradeTemplate();
            template.setId(gradeItem.getTemplateId());
            template.setLayer(layer);
            gradeTemplateMapper.updateGradeTemplate(template);
        }

        //gradeType的所有的父级别全部查询出来

        List<GradeType> gradeTypeList = gradeTypeMapper.selectGradeTypeByTemplateId(gradeItem.getTemplateId());
        if(gradeTypeList!=null &&gradeTypeList.size()>0){
            Map<Long,GradeType>parentTypeMap = new HashMap<>();
            for(GradeType tempType: gradeTypeList){
                parentTypeMap.put(tempType.getTypeId(),tempType);
            }
            Long parentTypeId = gradeItem.getTypeId();

            do{
                GradeType parentType = parentTypeMap.get(parentTypeId);
                if("2".equals(parentType.getScoreModel())){
                    Float weight = gradeItem.getWeight();
                    if(weight==null){
                        gradeItem.setWeight((float) parentType.getWeight());
                    }else {
                        gradeItem.setWeight(gradeItem.getWeight()* parentType.getWeight()/100);
                    }
                }
                parentTypeId = parentType.getParentId();
            }while (parentTypeId>0);
        }

        return gradeItemMapper.insertGradeItem(gradeItem);
    }

    public int assembleItemSixColumn(GradeItem gradeItem)
    {
        List<GradeType> allTypeList = gradeTypeMapper.selectGradeTypeAll();
        Map<Long,Long> childrenParentMap= new HashMap<Long,Long>();
        Map<Long,String> typeNameMap= new HashMap<Long,String>();
        Map<Long,GradeType> typeObjectMap= new HashMap<Long,GradeType>();

        for(GradeType gradeType: allTypeList){
            childrenParentMap.put(gradeType.getTypeId(),gradeType.getParentId());
            typeNameMap.put(gradeType.getTypeId(),gradeType.getTypeName());
            typeObjectMap.put(gradeType.getTypeId(),gradeType);
        }
        return getMaxColumnAndSetTypeName(gradeItem,typeObjectMap,childrenParentMap);
    }

    private int getMaxColumnAndSetTypeName(GradeItem gradeItem,Map<Long,GradeType> typeObjectMap,Map<Long,Long>childrenParentMap){
        int maxColumn = 0;
        List<GradeType>columonList = new ArrayList<GradeType>();
        Long parentId = gradeItem.getTypeId();
        do{
            maxColumn++;
            columonList.add(typeObjectMap.get(parentId));
            parentId = childrenParentMap.get(parentId);
        }while(parentId>0);

        for(int i=1;i<=maxColumn;i++){
            if(i==1){
                gradeItem.setFirstColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setFirstOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==2){
                gradeItem.setSecondColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setSecondOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==3){
                gradeItem.setThreeColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setThreeOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==4){
                gradeItem.setFourColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setFourOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==5){
                gradeItem.setFiveColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setFiveOrder(columonList.get(maxColumn-i).getTypeOrder());
            }else if(i==6){
                gradeItem.setSixColumn(columonList.get(maxColumn-i).getTypeName());
                gradeItem.setSixOrder(columonList.get(maxColumn-i).getTypeOrder());
            }
        }
        return maxColumn;
    }

    public int assembleItemSixColumn_New(GradeItem gradeItem)
    {
        List<GradeType> allTypeList = gradeTypeMapper.selectGradeTypeByTemplateId(gradeItem.getTemplateId());
        Map<Long,Long> childrenParentMap= new HashMap<Long,Long>();
        Map<Long,String> typeNameMap= new HashMap<Long,String>();
        Map<Long,GradeType> typeObjectMap= new HashMap<Long,GradeType>();

        for(GradeType gradeType: allTypeList){
            childrenParentMap.put(gradeType.getTypeId(),gradeType.getParentId());
            typeNameMap.put(gradeType.getTypeId(),gradeType.getTypeName());
            typeObjectMap.put(gradeType.getTypeId(),gradeType);
        }
        return getMaxColumnAndSetTypeName(gradeItem,typeObjectMap,childrenParentMap);
    }

    /**
     * 修改评分指标项
     * 
     * @param gradeItem 评分指标项
     * @return 结果
     */
    @Override
    public int updateGradeItem(GradeItem gradeItem)
    {
        gradeItem.setUpdateTime(DateUtils.getNowDate());

        //判断是否更改了评分分类
        GradeItem old_GradeItem=gradeItemMapper.selectGradeItemById(gradeItem.getId());
        gradeItem.setTemplateId(old_GradeItem.getTemplateId());
        if (!old_GradeItem.getTypeId().equals(gradeItem.getTypeId())){
            //更新一级类型、二级类型....及对应的排序号
            int layer = assembleItemSixColumn_New(gradeItem);

            //gradeType的所有的父级别全部查询出来，更新权重
            List<GradeType> gradeTypeList = gradeTypeMapper.selectGradeTypeByTemplateId(gradeItem.getTemplateId());
            if (gradeTypeList != null && gradeTypeList.size() > 0) {
                Map<Long, GradeType> parentTypeMap = new HashMap<>();
                for (GradeType tempType : gradeTypeList) {
                    parentTypeMap.put(tempType.getTypeId(), tempType);
                }
                Long parentTypeId = gradeItem.getTypeId();
                gradeItem.setWeight(null);

                do {
                    GradeType parentType = parentTypeMap.get(parentTypeId);
                    if ("2".equals(parentType.getScoreModel())) {
                        Float weight = gradeItem.getWeight();
                        if (weight == null) {
                            gradeItem.setWeight((float) parentType.getWeight());
                        } else {
                            gradeItem.setWeight(gradeItem.getWeight() * parentType.getWeight() / 100);
                        }
                    }
                    parentTypeId = parentType.getParentId();
                } while (parentTypeId > 0);
            }
        }else{
            gradeItem.setFirstColumn(old_GradeItem.getFirstColumn());
            gradeItem.setFirstOrder(old_GradeItem.getFirstOrder());

            gradeItem.setSecondColumn(old_GradeItem.getSecondColumn());
            gradeItem.setSecondOrder(old_GradeItem.getSecondOrder());

            gradeItem.setThreeColumn(old_GradeItem.getThreeColumn());
            gradeItem.setThreeOrder(old_GradeItem.getThreeOrder());

            gradeItem.setFourColumn(old_GradeItem.getFourColumn());
            gradeItem.setFourOrder(old_GradeItem.getFourOrder());

            gradeItem.setFiveColumn(old_GradeItem.getFiveColumn());
            gradeItem.setFiveOrder(old_GradeItem.getFiveOrder());

            gradeItem.setSixColumn(old_GradeItem.getSixColumn());
            gradeItem.setSixOrder(old_GradeItem.getSixOrder());
        }

        gradeItemMapper.updateGradeItem(gradeItem);

        //更新评分模版层级
        return  updateGradeTemplateLayer(gradeItem.getTemplateId());
    }

    /**
     * 批量删除评分指标项
     * 
     * @param ids 需要删除的评分指标项主键
     * @return 结果
     */
    @Override
    public int deleteGradeItemByIds(String ids)
    {
        String[] itemIdArray=Convert.toStrArray(ids);
        List<GradeItem> gradeItemList=new ArrayList<GradeItem>();
        for(int i=0;i<itemIdArray.length;i++) {
            Long itemId = Long.parseLong(itemIdArray[i]);
            GradeItem gradeItem=gradeItemMapper.selectGradeItemById(itemId);
            if (gradeItem!=null) {
                gradeItemList.add(gradeItem);
            }
        }

        gradeItemMapper.deleteGradeItemByIds(Convert.toStrArray(ids));
        for(int j=0;j<gradeItemList.size();j++) {
            updateGradeTemplateLayer(gradeItemList.get(j).getTemplateId());
        }
        return  1;
    }

    /**
     * 删除评分指标项信息
     * 
     * @param id 评分指标项主键
     * @return 结果
     */
    @Override
    public int deleteGradeItemById(Long id)
    {
        return gradeItemMapper.deleteGradeItemById(id);
    }

    @Override
    public int countGradeItemByTemplateIds(String[]  templateIds) {
        return gradeItemMapper.countGradeItemByTemplateIds(templateIds);
    }

    @Override
    public int updateGradeDeductFlag(GradeItem gradeItem) {
        return gradeItemMapper.updateGradeDeductFlag(gradeItem);
    }

    private int  updateGradeTemplateLayer(Long templateId){
        //更新评分模版层级
        List<GradeItem> gradeItemList = gradeItemMapper.selectGradeItemByTemplateId(templateId);
        int maxLayer = 0;
        int layer = 0;
        for (int j = 0; j < gradeItemList.size(); j++) {
            GradeItem gradeItem = gradeItemList.get(j);
            layer = 0;
            if (gradeItem != null) {
                if (gradeItem.getFirstColumn() != null && !gradeItem.getFirstColumn().equals("")) {
                    layer = 1;
                }
                if (gradeItem.getSecondColumn() != null && !gradeItem.getSecondColumn().equals("")) {
                    layer = 2;
                }
                if (gradeItem.getThreeColumn() != null && !gradeItem.getThreeColumn().equals("")) {
                    layer = 3;
                }
                if (gradeItem.getFourColumn() != null && !gradeItem.getFourColumn().equals("")) {
                    layer = 4;
                }
                if (gradeItem.getFiveColumn() != null && !gradeItem.getFiveColumn().equals("")) {
                    layer = 5;
                }
                if (gradeItem.getSixColumn() != null && !gradeItem.getSixColumn().equals("")) {
                    layer = 6;
                }
            }
            if (layer > maxLayer) {
                maxLayer = layer;
            }
        }

        GradeTemplate gradeTemplate = gradeTemplateMapper.selectGradeTemplateById(templateId);
        GradeTemplate template = new GradeTemplate();
        template.setId(templateId);
        template.setLayer(maxLayer);
        return  gradeTemplateMapper.updateGradeTemplate(template);
    }
}
